package com.noble.glamour.ui.agora.act;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.WindowManager;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.noble.glamour.R;
import com.noble.glamour.bean.center.user.light.UserLight;
import com.noble.glamour.bean.center.user.light.UserLightList;
import com.noble.glamour.module.logic.application.App;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.logic.baseui.LoadingDialog;
import com.noble.glamour.module.logic.config.UrlParam;
import com.noble.glamour.module.logic.request.HttpResponse;
import com.noble.glamour.module.logic.request.RequestComplete;
import com.noble.glamour.ui.agora.RtcUIShow;
import com.noble.library.utils.UIUtil;
import com.noble.glamour.ui.agora.act.base.RtcBaseActivity;
import com.noble.glamour.ui.agora.act.bean.Accept;
import com.noble.glamour.ui.agora.manager.RtcMessageMgr;
import com.noble.glamour.ui.agora.model.AgoraConstant;
import com.noble.glamour.ui.agora.util.RtcJointChannel;
import com.noble.glamour.ui.agora.util.RtcSubUtil;
import com.noble.glamour.ui.agora.util.RtcTimerUtil;
import com.noble.glamour.ui.utils.NoDoubleClickListener;
import com.noble.library.image.ImageLoader;
import com.noble.library.log.PToast;
import com.noble.library.observe.MsgMgr;
import com.noble.library.observe.MsgType;
import com.noble.library.observe.PObserver;
import com.noble.library.utils.BitmapUtil;
import com.noble.library.view.CustomFrameLayout;

import java.util.Map;

/**
 * 邀请 / 受邀 / 音频通话页面
 * Created by Su on 2017/3/19.
 */
public class RtcInitActivity extends RtcBaseActivity implements PObserver, RequestComplete {

    private LinearLayout chatWaiting;        // 等待通话
    private TextView chatBeInvited;          // 被邀请人提示
    private ImageView vipStatus;             // vip状态
    private ImageView imgBg;                 // 背景头像
    private ImageView imgHead;               // 头像
    private TextView tvName;                 // 昵称
    private CustomFrameLayout bottomLayout;  // 底部状态布局切换
    private Chronometer inviteCountUp, chatCountUp;

    // 聊天数据
    private UserLight infoLight; // 对方简略信息
    private boolean isRelease = true;      // 是否释放资源标志：当需要跳到视频页面时，无需释放资源

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.p1_chat_wait);
        addListener();
        initView();
        initBottom();
    }

    private void initView() {
        vipStatus = (ImageView) findViewById(R.id.iv_vip_status);
        chatWaiting = (LinearLayout) findViewById(R.id.chat_waiting);
        chatBeInvited = (TextView) findViewById(R.id.chat_be_invited);
        findViewById(R.id.iv_shrink_narrow).setVisibility(View.VISIBLE);
        findViewById(R.id.iv_shrink_narrow).setOnClickListener(listener);

        // 个人信息
        imgBg = (ImageView) findViewById(R.id.iv_bg);
        Bitmap bitmap = BitmapUtil.getDecodeBitmap(this, R.drawable.p1_default_bg, 320, 480);
        UIUtil.setBackground(imgBg, new BitmapDrawable(null, bitmap));
        imgHead = (ImageView) findViewById(R.id.iv_head);
        tvName = (TextView) findViewById(R.id.tv_name);

        // 计费信息
        if (config().mInviteType == AgoraConstant.RTC_CHAT_BEINVITE) {
            TextView tvPrice = (TextView) findViewById(R.id.chat_price);
            TextView tvTips = (TextView) findViewById(R.id.tips_pay);
            if (config().mChatPrice != 0) {
                tvPrice.setText(getString(R.string.tip_chat_wait_price, config().mChatPrice));
                tvPrice.setVisibility(View.VISIBLE);
                tvTips.setVisibility(View.VISIBLE);
            }
        }

        // 邀请方：往本地插入一条消息
        if (config().mInviteType == AgoraConstant.RTC_CHAT_INVITE) {
            ModuleMgr.getChatMgr().sendVideoMsgLocalSimulation(String.valueOf(config().mOtherId), config().mChatType, config().mVcid);
        }

        // 计时控件
        inviteCountUp = (Chronometer) findViewById(R.id.ch_inv_time);
        chatCountUp = (Chronometer) findViewById(R.id.ch_count_time);
        RtcTimerUtil.getInstance().addTimer(inviteCountUp);
        RtcTimerUtil.getInstance().addTimer(chatCountUp);

        findViewById(R.id.btn_invite_hangup).setOnClickListener(listener);
        findViewById(R.id.btn_beinvite_hangup).setOnClickListener(listener);
        findViewById(R.id.btn_answer).setOnClickListener(listener);

        RtcJointChannel.getInstance().reqUserInfo(this);
    }

    /**
     * 同步操作问题
     */
    private void addListener() {
        // 通话失效
        if (RtcMessageMgr.getInstance().leaveChat()) {
            PToast.showLong(getString(R.string.chat_tips_user_hangup));
            finish();
            return;
        }

        // 已收到对方同意通话消息
        if (RtcMessageMgr.getInstance().inChat()) {
            RtcJointChannel.getInstance().joinChannelPrepare(false);
            if (config().mChatType == AgoraConstant.RTC_CHAT_VIDEO) {
                RtcUIShow.showRtcVideoActFinish(App.activity);
            } else {
                RtcUIShow.showRtcVoiceActFinish(App.activity);
            }
            return;
        }
        MsgMgr.getInstance().attach(this);
    }

    private void initBottom() {
        RtcSubUtil.getInstance().playSound();  // 开启铃声
        bottomLayout = (CustomFrameLayout) findViewById(R.id.frame_layout);
        bottomLayout.showOfIndex(config().mInviteType);

        switch (config().mInviteType) {
            case AgoraConstant.RTC_CHAT_INVITE:   // 邀请
                chatWaiting.setVisibility(View.VISIBLE);
                RtcTimerUtil.getInstance().startStatisInvTime();
                inviteCountUp.setBase(SystemClock.elapsedRealtime() - config().mInviteTime);
                inviteCountUp.start();
                break;

            case AgoraConstant.RTC_CHAT_BEINVITE: // 被邀请
                chatBeInvited.setVisibility(View.VISIBLE);
                if (config().mChatType == AgoraConstant.RTC_CHAT_VOICE) {
                    chatBeInvited.setText(getString(R.string.chat_voice_invite));
                    return;
                }
                chatBeInvited.setText(getString(R.string.chat_video_invite));
                break;
        }
    }

    /**
     * 点击事件
     */
    private NoDoubleClickListener listener = new NoDoubleClickListener() {
        @Override
        public void onNoDoubleClick(View v) {
            switch (v.getId()) {

                case R.id.btn_invite_hangup:   // 邀请方挂断按钮, 若未成功建立连接时不能调用stop接口
                case R.id.btn_beinvite_hangup: // 被邀请方拒绝按钮
                    RtcJointChannel.getInstance().rejectChat();
                    break;

                case R.id.btn_answer:          // 被邀请方接听按钮
                    RtcJointChannel.getInstance().acceptChat(RtcInitActivity.this);
                    break;

                case R.id.iv_shrink_narrow: // 最小化
                    if (checkOverLaysPermission())
                        ModuleMgr.getRtcEnginMgr().startRtcFloatService();
                    break;
            }
        }
    };

    /**
     * 通信跳转
     */
    private void startChat() {
        isRelease = false;
        RtcJointChannel.getInstance().joinChannelPrepare(true);
        if (config().mChatType == AgoraConstant.RTC_CHAT_VIDEO)
            RtcUIShow.showRtcVideoActFinish(this);
        else
            RtcUIShow.showRtcVoiceActFinish(this);
    }

    /**
     * 通话状态消息
     */
    @Override
    public void onMessage(String key, Object value) {
        switch (key) {
            case MsgType.MT_Rtc_Chat_Status:
                Map<String, Object> data = (Map<String, Object>) value;
                switch ((int) data.get("type")) {
                    case 2:     // 同意加入
                        startChat();
                        break;

                    case 3:     // 拒絕加入
                    case 4:     // 挂断
                    default:
                        finish();
                        break;
                }
                break;

            case MsgType.MT_Rtc_Chat_Close_Msg:
                finish();
                break;

            case MsgType.MT_Rtc_Chat_Timer_Msg:
                if ((int) value == AgoraConstant.TIMER_INVITE) {
                    long totalSec = config().mInviteTime / 1000;
                    if (totalSec == AgoraConstant.CHAT_TIME_TIPS) { // 计时30s, 展示提示信息
                        PToast.showCenterShort(App.activity.getString(R.string.chat_waiting_suggest));
                    }

                    if (totalSec == AgoraConstant.CHAT_TIME_AUTO_HUANGUP) { // 计时60s未接听，自动挂断
                        RtcJointChannel.getInstance().reqTimeOutChat();
                    }
                }
                break;
        }
    }

    /**
     * 个人信息请求结果回调
     */
    @Override
    public void onRequestComplete(HttpResponse response) {
        if (response.getUrlParam() == UrlParam.reqUserInfoSummary) {
            if (!response.isOk()) return;
            UserLightList list = (UserLightList) response.getBaseData();
            if (list.getLightList() != null && list.getLightList().size() > 0) {
                infoLight = list.getLightList().get(0);
                // 更新布局
                ImageLoader.loadBlur(this, infoLight.getAvatar(), imgBg, 8, R.drawable.p1_default_bg);
                ImageLoader.loadRoundAvatar(this, infoLight.getAvatar(), imgHead);
                tvName.setText(infoLight.getNickname());
//                vipStatus.setVisibility(infoLight.isVip() ? View.VISIBLE : View.GONE);
            }
            return;
        }

        // 接受邀请
        if (response.getUrlParam() == UrlParam.reqAcceptChat) {
            if (response.isOk()) {
                Accept accept = (Accept) response.getBaseData();
                config().mChannelKey = accept.getChannelKey();  // 保存到配置文件
                config().msgVer = accept.getMsgVer();
                startChat();
                return;
            }
            PToast.showShort(response.getMsg() == null ? getString(R.string.chat_join_fail_tips) : response.getMsg());
            RtcJointChannel.getInstance().rejectChat();
        }
    }

    @Override
    public void finish() {
        super.finish();
        LoadingDialog.closeLoadingDialog();
        MsgMgr.getInstance().detach(this);
        RtcSubUtil.getInstance().stopPlay();

        // 处于悬浮窗、跳到视频页面， 则只需释放本地Timer计时
        if (RtcJointChannel.getInstance().getFloatStatus() || !isRelease) {
            ModuleMgr.getRtcEnginMgr().releaseLocalTimer();
            return;
        }

        // 全部回收
        ModuleMgr.getRtcEnginMgr().releaseAll();
    }
}
